<?php
/**
 * Created by PhpStorm.
 * User: Dave
 * Date: 2018/4/23
 * Time: 16:41
 */

namespace Biz\validate;

use Biz\model\ShopSpecial as mShopSpecial;

class ShopSpecial extends \Doraemon\pockets\validate\Base
{
    public static function rules()
    {
        return [

            ['special_title', 'required', null, '请填写专题标题', ['create', 'update']],
            ['special_title', 'length', '1,20', '商品专题标题输入有误，最多不超过20个汉字', ['create', 'update']],

            ['share_title', 'required', null, '请填写分享标题', ['create', 'update']],
            ['share_title', 'length', '1,20', '分享标题输入有误，最多输入20个汉字', ['create', 'update']],

            ['share_desc', 'required', null, '请填写分享描述文字', ['create', 'update']],
            ['share_desc', 'length', '1,200', '分享描述输入有误，最多输入20个汉字', ['create', 'update']],

            ['shop_img', 'required', null, '请选择首页图片', ['create', 'update']],
            ['special_info_img', 'required', null, '请选择专题详情图片', ['create', 'update']],
            ['share_img', 'required', null, '请选择分享图片', ['create', 'update']],

            ['relation_id', 'callback', ['callback' => [new self(), 'checkRelationId']], '请输入正确的关联活动id', ['create', 'update']],

            ['start_time', 'required', null, '请选择开始日期', ['create', 'update']],
            ['end_time', 'required', null, '请选择结束日期', ['create', 'update']],

            ['sort', 'required', null, '请填写权重值', ['create', 'update']],
            ['sort', 'callback', ['callback' => [new self(), 'checkSort']], '当前权重值已存在', ['create', 'update']],

        ];
    }

    public function checkSort($value, $valueIdentifier, $allData)
    {
        $specialId = '';
        if (!empty($allData['specialId'])){
            $specialId = $allData['specialId'];
        }

        $sort = mShopSpecial::checkSort($allData['sort'], $specialId);
        if ($sort){

            return false;
        }
        return true;

    }

    public function checkRelationId($value, $valueIdentifier, $allData)
    {
        if(empty($value)) {
            return true;
        }

        $value = explode(',', $value);

        if(!is_array($value)) {
            return false;
        }

        foreach($value as $val) {
            if($val != $allData['specialId']) {
                $ids[] = $val;
            }
        }

        $result = array_map(function($v){
            $result = mShopSpecial::getSpecialInfoById($v,mShopSpecial::TYPE_SPECIAL_GOODS);
            return $result;
        }, $ids);

        if(count($ids) != count(array_filter($result))) {
            return false;
        }

        return true;
    }
}